/**
 * 查询商品
 */
Vue.component('yl-goods', {
    template: `<el-dialog id="ylGoods"  title="商品选择" :visible.sync="visibleDialog" width="80vw">
        <el-form :inline="true" :form="form">
            <el-form-item>
                <el-input v-model.trim="Article_Name" clearable placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select v-model.trim="selectSupplier" collapse-tags multiple style="width: 100%;" clearable placeholder="请选择供应商">
                    <el-option v-for="item in supplier" :key="item.Supplier_SerialNumber" :label="item.Supplier_Name" :value="item.Supplier_SerialNumber"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select clearable v-model.trim="form.Brand_SerialNumber" placeholder="请选择商品品牌" filterable style="width: 100%">
                    <el-option v-for="(item,index) in brand" :key="index" :label="item.Brand_Name" :value="item.Brand_SerialNumber"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-cascader v-model="selectclassify" filterable collapse-tags clearable placeholder="商品分类"
                    :props="defaultProps" :options="classify" style="width: 300px"></el-cascader>
            </el-form-item>
            <el-form-item>
                <el-row style="width: 217px;">
                    <el-col :span="11">
                        <el-input v-model.trim="form.gross_margin1" clearable placeholder="毛利率%" />
                    </el-col>
                    <el-col style="text-align: center;" :span="2">-</el-col>
                    <el-col :span="11">
                        <el-input v-model.trim="form.gross_margin2" clearable placeholder="毛利率%" />
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item>
                <el-row style="width: 217px;">
                    <el-col :span="11">
                        <el-input v-model.trim="form.discount1" clearable placeholder="商品折扣%" />
                    </el-col>
                    <el-col style="text-align: center;" :span="2">-</el-col>
                    <el-col :span="11">
                        <el-input v-model.trim="form.discount2" clearable placeholder="商品折扣%" />
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item>
                <el-row style="width: 217px;">
                    <el-col :span="11">
                        <el-input v-model.trim="form.Purchase_Unit_Price1" clearable placeholder="一件代发价" />
                    </el-col>
                    <el-col style="text-align: center;" :span="2">-</el-col>
                    <el-col :span="11">
                        <el-input v-model.trim="form.Purchase_Unit_Price2" clearable placeholder="一件代发价" />
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item>
                <el-row style="width: 217px;">
                    <el-col :span="11">
                        <el-input v-model.trim="form.Sales_Unit_Price1" clearable placeholder="平台价" />
                    </el-col>
                    <el-col style="text-align: center;" :span="2">-</el-col>
                    <el-col :span="11">
                        <el-input v-model.trim="form.Sales_Unit_Price2" clearable placeholder="平台价" />
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="onSerach">查询</el-button>
            </el-form-item>
            <!--<el-form-item>
                <el-upload class="upload-demo" accept=".xlsx" ref="upload" action="" :show-file-list="false" :on-change="handleChange" :auto-upload="false">
                    <el-button :disabled="loading" slot="trigger" type="primary">导入</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="download">下载模板</el-button>
            </el-form-item>-->
        </el-form>
        <el-table ref="multipleTable" :data="tableData.slice((form.page-1)*form.limit,form.page*form.limit)"  :row-key="row=>row.Supplier_Article_SerialNumber" stripe border height="45vh" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" :reserve-selection="true" width="50"></el-table-column>
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column align="center" prop="Supplier_Article_SerialNumber" show-overflow-tooltip width="170" label="供应商品内码"></el-table-column>
            <el-table-column align="center" prop="Supplier_Name" show-overflow-tooltip width="170" label="供应商名称"></el-table-column>
            <el-table-column align="center" prop="Article_Name" show-overflow-tooltip width="170" label="商品名称"></el-table-column>
            <el-table-column align="center" prop="Specifications_Name" show-overflow-tooltip width="170" label="规格名称"></el-table-column>
            <el-table-column align="center" prop="Picture_URL" width="140" align="center" label="商品封面">
                <template v-slot="{row}">
                    <el-image fit="contain" :src="BASE_IMG + row.Picture_URL" style="width:100px;height: 100px;"></el-image>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="JDCOM_Unit_Price" show-overflow-tooltip width="170" label="商品京东价"></el-table-column>
            <el-table-column align="center" prop="JDCOM_URL" show-overflow-tooltip width="170" label="商品京东链接"></el-table-column>
            <el-table-column align="center" prop="JDCOM_Unit_Price1" show-overflow-tooltip width="170" label="规格京东价"></el-table-column>
            <el-table-column align="center" prop="JDCOM_URL1" show-overflow-tooltip width="170" label="规格京东链接"></el-table-column>
            <el-table-column align="center" prop="Group" show-overflow-tooltip width="170" label="是否参与团购"></el-table-column>
            <el-table-column align="center" show-overflow-tooltip width="170" label="是否上架">
                <template v-slot="{row}">
                    {{row.Shelf=='0'?'已上架':'未上架'}}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="Purchase_Unit_Price" width="150" show-overflow-tooltip label="一键代发价(元)"></el-table-column>
            <el-table-column align="center" prop="Sales_Unit_Price" width="150"  show-overflow-tooltip label="平台价(元)"></el-table-column>
            <el-table-column align="center" label="折扣率"  width="150" >
                <template v-slot="{row}">
                    {{row.JDCOM_Unit_Price1>0&&row.Sales_Unit_Price>0?(accDiv(row.Sales_Unit_Price,row.JDCOM_Unit_Price1)*100).toFixed(2) + '%':'-'}}
                </template>
            </el-table-column>
            <el-table-column align="center" label="毛利率"  width="150" >
                <template v-slot="{row}">
                    {{row.Purchase_Unit_Price>0&&row.Sales_Unit_Price>0?(accSub(1,accDiv(row.Purchase_Unit_Price,row.Sales_Unit_Price))*100).toFixed(2)+'%':'-'}}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
                <template v-slot="{row,$index}">
                    <el-button size="small" :disabled="loading" type="danger" @click="handleRemove($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="form.page" :page-sizes="[10, 30 , 60 ,100, 200, 300, 400]" :page-size="form.limit"
            layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
        </el-pagination>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)">取消</el-button>
            <el-button type="primary" @click="submit()">确定</el-button>
        </span>
    </el-dialog>`,
    props: ['data', 'edit', 'visible'],
    data() {
        return {
            visibleDialog: false,
            tableData: [],//详情
            form: {
                SQLSerialNumber: "A_business_supplier_article5",
                Condition: '',
                ExtensionCondition: '',
                page:1,
                limit:10,
                gross_margin1:'',
                gross_margin2:'',
                discount1:'',
                discount2:'',
                Purchase_Unit_Price1:'',
                Purchase_Unit_Price2:'',
                Sales_Unit_Price1:'',
                Sales_Unit_Price2:'',
            },
            total:0,
            activeName:"1",
            loading: false,
            supplier:[],//全部品牌
            brand:[],
            classify:[],//全部类别
            screen:[{
                label:'采购价格高到低',
                value:'0'
            },{
                label:'采购价格低到高',
                value:'1'
            }],
            selectSupplier:[],//已选品牌
            selectclassify:[],//已选分类
            Article_Name:'',//商品名称
            selectScreen:'',//已选筛选类型
            defaultProps:{
                children: 'Children',
                label: 'Classify_Name',
                value: 'Classify_SerialNumber',
                multiple: true,
            },
            multipleSelection:[],
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val);
            if (val) {
                this.tableData = [];
            }
        },
    },
    methods: {
        onSerach(){
            // let classify = []
            // this.selectclassify.forEach(item => {
            //     classify = uniqueArr([...classify,...item]);
            // })
            let sql = `and business_article_info.Article_Name LIKE '%${this.Article_Name}%'`
            //去重
            if (this.selectclassify.length> 0) {
                let str = "";
                this.selectclassify.forEach(item =>{
                    if (str) {
                        str = str + " or business_article_classify.Classify_SerialNumber = '" + item[item.length - 1] + "' \r\n"
                    } else {
                        str = "business_article_classify.Classify_SerialNumber = '" + item[item.length - 1] + "' \r\n"
                    }
                   
                })
                sql = sql + " and (" + str + ") \r\n";
            }
            // if(classify.length > 0){
            //     let str = "";
            //     classify.forEach((item,index)=>{
            //         if (index==0) {
            //             str =  "business_article_classify.Classify_SerialNumber = '"+ item +"' \r\n"
            //         }else {
            //             str = str + " or business_article_classify.Classify_SerialNumber = '"+ item +"' \r\n"
            //         }
            //     })
            //     sql = sql + "and (" + str + ")\r\n"
            // }
            if (this.selectSupplier.length > 0) {
                let str = "";
                this.selectSupplier.forEach((item,index)=>{
                    if (index==0) {
                        str =  "business_supplier_info.Supplier_SerialNumber = '"+ item +"' \r\n"
                    }else {
                        str = str + " or business_supplier_info.Supplier_SerialNumber = '"+ item +"' \r\n"
                    }
                })
                sql = sql + "and (" + str + ")\r\n"
            }
            //筛掉已选商品
            if(this.data.length > 0){
                this.data.forEach(item=>{
                    sql = sql + "\r\nand business_supplier_article.Supplier_Article_SerialNumber <> '"+item.Supplier_Article_SerialNumber+"' "
                })
            }
            //类别
            if(this.form.Brand_SerialNumber){
                sql = sql + "\r\nand business_article_info.Brand_SerialNumber = '" +this.form.Brand_SerialNumber+ "'"
            }

             //毛利率
             if (this.form.gross_margin1) {
                sql = sql + " and CAST(IFNULL(ROUND((1 - business_daily_purchase_unitprice.Purchase_Unit_Price/business_daily_execute_unitprice.Sales_Unit_Price)*100),'0') As FLOAT) >= '"+this.form.gross_margin1+"'";
            }
            if (this.form.gross_margin2) {
                sql = sql + " and CAST(IFNULL(ROUND((1 - business_daily_purchase_unitprice.Purchase_Unit_Price/business_daily_execute_unitprice.Sales_Unit_Price)*100),'0') As FLOAT) <= '"+this.form.gross_margin2+"'";
            }
            //区间
            if (this.form.discount1) {
                sql = sql + " and CAST(IFNULL(ROUND(business_daily_execute_unitprice.Sales_Unit_Price/business_article_specifications.JDCOM_Unit_Price*100),'0') As FLOAT) >= '"+this.form.discount1+"'";
            }
            if (this.form.discount2) {
                sql = sql + " and CAST(IFNULL(ROUND(business_daily_execute_unitprice.Sales_Unit_Price/business_article_specifications.JDCOM_Unit_Price*100),'0') As FLOAT) <= '"+this.form.discount2+"'";
            }
            //区间
            if (this.form.Purchase_Unit_Price1 > 0) {
                sql = sql + " and CAST(IFNULL(business_daily_purchase_unitprice.Purchase_Unit_Price,'0') As FLOAT) >= '" + this.form.Purchase_Unit_Price1 + "' "
            }
            if (this.form.Purchase_Unit_Price2 > 0) {
                sql = sql + " and CAST(IFNULL(business_daily_purchase_unitprice.Purchase_Unit_Price,'0') As FLOAT) <= '" + this.form.Purchase_Unit_Price2 + "' "
            }
            if (this.form.Sales_Unit_Price1 > 0) {
                sql = sql + " and CAST(IFNULL(business_daily_execute_unitprice.Sales_Unit_Price,'0') As FLOAT) >= '" + this.form.Sales_Unit_Price1 + "' "
            }  
            if (this.form.Sales_Unit_Price2 > 0) {
                sql = sql + " and CAST(IFNULL(business_daily_execute_unitprice.Sales_Unit_Price,'0') As FLOAT) <= '" + this.form.Sales_Unit_Price2 + "' "
            }
            // if (this.selectScreen!='') {
            //     if (this.selectScreen=='0') {//相同商品取采购价格高到低
            //         sql = sql + "\r\nORDER BY business_article_info.Operation_Datetime DESC,business_daily_purchase_unitprice.Purchase_Unit_Price DESC,business_supplier_article.Article_SerialNumber,business_supplier_article.Article_Specifications_SerialNumber"

            //     }else if(this.selectScreen=='1'){//相同采购价格低到高
            //         sql = sql + "\r\nORDER BY business_article_info.Operation_Datetime DESC,business_daily_purchase_unitprice.Purchase_Unit_Price,business_supplier_article.Article_SerialNumber,business_supplier_article.Article_Specifications_SerialNumber"
            //     }
            // } else {
            //     sql = sql + "\r\nORDER BY business_article_info.Operation_Datetime DESC,business_supplier_article.Article_SerialNumber,business_supplier_article.Article_Specifications_SerialNumber"
            // }
            this.form.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)))
            this.getList(this.form);
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleSelectionChange(val){
            this.multipleSelection = val;
        },
        handleRemove(index){
            this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
        },  
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                //1.查询商品信息，并展示到页面上
                let str = "";//商品内码
                json.forEach(item=>{
                    if (item['商品内码']) {
                        if (str) {
                            str = str+ " or business_article_info.Article_SerialNumber = '"+item['商品内码']+"'\r\n"
                        }else{
                            str = " business_article_info.Article_SerialNumber = '"+item['商品内码']+"'\r\n"
                        }
                    }
                })
                let sql = "and (" + str + ")";
                that.form.ExtensionCondition =  window.btoa(unescape(encodeURIComponent(sql)));
                that.getList(that.form);
            }
        },
        getList(data) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result;
                    that.$refs.multipleTable.clearSelection();
                    // that.tableData.forEach(item=>{
                    //     if (that.data.some(i=>i.Supplier_Article_SerialNumber == item.Supplier_Article_SerialNumber)) {
                    //         that.$refs.multipleTable.toggleRowSelection(item);
                    //     }
                    // })
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submit(){
            if (this.multipleSelection.length > 0) {
                this.$emit('success',this.multipleSelection);
                this.$emit('update:visible', false)
            }else{
                this.$message({
                    message: '请先选择商品',
                    type: 'warning'
                })
            }
        },
        download(){
            window.location.href = './download/导入商品编号查询商品.xlsx'
        },
        getData(){
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_brand',
                    Condition:"Row_Status='0'",
                },
                success: function (res) {
                    that.brand = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_supplier_info',
                    Condition:"Row_Status='0'",
                },
                success: function (res) {
                    that.supplier = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/getAllClassify`,
                type: 'GET',
                success: function (data) {
                    that.classify = data
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        }
    },
    mounted(){
        this.getData();
    },
})